<template>
    <div style="display: flex;justify-content: space-between;">
        <a-form size="small" :model="pageData" layout="inline" style="margin-bottom: 10px;" ref="formRef">
            <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader" />
            <a-form-item label="日期">
                <a-range-picker class="bacClass" v-model="pageData.createTimeArr" style="width:260px" />
            </a-form-item>
        </a-form>
        <Toolbar v-if="tabKey === 1" :items="['查询']" @select="selectHandle"></Toolbar>
        <Toolbar v-if="tabKey === 2" :items="['查询', '提交厂长审核']" @select="selectHandle" @audit="submitAudit"></Toolbar>
    </div>
    <div class="cssTable">
        <a-tabs :lazy-load="true" :justify="true" :default-active-key="tabKey" @change="tabChange">
            <a-tab-pane title="待处理" :key="1">
                <a-spin :loading="pageData.pageLoading" tip="加载中" dot
                    style="height:100%;width: 98%;z-index:999 ;margin-left: 13px;">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        :style="{ height: pageData.rHeight - 220 + 'px' }" :suppressDragLeaveHidesColumns="true"
                        rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="pageData.tableList" :columnDefs="tableColumns"
                        :localeText="localeText1"></AgGridVuesCopys>
                </a-spin>
            </a-tab-pane>
            <a-tab-pane title="已处理" :key="2">
                <a-spin :loading="pageData.pageLoading" tip="加载中" dot
                    style="height:100%;width: 98%;z-index:999 ;margin-left: 13px;">
                    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                        :style="{ height: pageData.rHeight - 220 + 'px' }" :suppressDragLeaveHidesColumns="true"
                        rowSelection="multiple" @grid-ready="gridReady2" :defaultColDef="defaultColDef"
                        class='ag-theme-alpine' :rowData="pageData.tableList" :columnDefs="tableColumns2"
                        :localeText="localeText1"></AgGridVuesCopys>
                </a-spin>
            </a-tab-pane>
        </a-tabs>
    </div>
    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
        @change="PageSize" @page-size-change="change1" style="justify-content: center;margin-top:12px;"
        :page-size="size" :current="page" />

    <!-- 处理意见 -->
    <a-drawer style="z-index:999" :drawer-style="{ 'zIndex': 999 }" :mask-closable="false"
        popup-container=".arco-tabs-content" height="100%" :visible="pageData.showAdd" placement="bottom" unmountOnClose
        @cancel="pageData.showAdd = false">
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <el-button :icon="EditPen" @click="editRow()" v-if="pageData.sideTitle === '处理意见汇总'">修改</el-button>
        <el-button :icon="CirclePlus" @click="addRow()" type="success"
            v-if="pageData.sideTitle === '处理意见填写'">新增行</el-button>
        <el-button :icon="Delete" @click="delRow()" v-if="pageData.sideTitle === '处理意见填写'">删除</el-button>
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot
            style="height:100%;width: 98%;z-index:999 ;margin-left: 13px;">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                :suppressDragLeaveHidesColumns="true" style="height:93%;margin-top: 10px;" @grid-ready="gridReadyCL"
                :defaultColDef="defaultColDef2" class='ag-theme-alpine' :rowData="pageData.reasonList"
                :columnDefs="tableColumnsCL" :localeText="localeText1">
            </AgGridVuesCopys>
        </a-spin>
        <template #footer>
            <a-button @click="pageData.showAdd = false">取消</a-button>
            <a-button type="primary" @click="sideOk" v-if="pageData.sideTitle != '处理意见汇总'">保存</a-button>
        </template>
    </a-drawer>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, Ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { FormInstance } from "@arco-design/web-vue/es/form";
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { Search, CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
    rHeight: 0,
    pageLoading: false,
    tableList: [],
    sideTitle: '',
    sideTitle2: '',
    showAdd: false,
    status: 1,
    reasonList: [],
    itemsList: [],
    companyId: null,
    companyName: '',
    handlerDepartmentCodes: null,
    createTimeArr: null,
    itemsVisible: false,
    records: null,
    urlData: '',
    fileList: [],
})
const dataForm: any = reactive({
    problemId: null,
    employeeCode: '',
    employeeName: '',
    handlerOrderCodes: '',
    companyId: null,
    orderList: [],
    status: null,
})

//分页
const total = ref(0);
const page = ref(1);
const size = ref(10);
function PageSize(val: any) {
    page.value = val
    doRefresh();
}
function change1(val: any) {
    size.value = val
    doRefresh();
}

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
}

//未判责
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}
const tableColumns: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    {
        headerName: "来源", width: 150,
        cellRenderer: {
            template: `<span> {{ val.createUser=== 'SYN' ? '系统创建' : '手动创建' }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
    },
    { headerName: "事故单号", field: "problemCode", width: 150, },
    { headerName: "日期", field: "createTime", width: 150, },
    { headerName: "公司", field: "companyName", width: 150, },
    { headerName: "部门", field: "departmentName", width: 150, },
    { headerName: "员工工号", field: "staffCode", width: 150, },
    { headerName: "员工姓名", field: "staffName", width: 150, },
    { headerName: "机台号", field: "machineCode", width: 150, },
    { headerName: "织布单号", field: "planOrderCode", width: 150, },
    { headerName: "坯布编号", field: "greyCode", width: 150, },
    { headerName: "坯布名称", field: "greyName", width: 150, },
    {
        headerName: "数量", width: 150,
        cellRenderer: () => {
            return "<span>" + 1 + "</span>";
        },
    },
    {
        headerName: "单位", width: 150,
        cellRenderer: () => {
            return "<span>" + '匹' + "</span>";
        },
    },
    { headerName: "问题原因", field: "defectReason", width: 150, },
    { headerName: "问题补充", field: "questionSupplement", width: 150, },
    {
        headerName: "疵布重量",
        field: "lowLevelWeight",
        width: 150,
    },
    {
        headerName: "实际转数", width: 150,
        cellRenderer: (params: any) => {
            let val = params.data.convolution1 + params.data.convolution2
            return "<span>" + val + "</span>";
        },
    },
    { headerName: "责任工序", field: "handlerOrderNames", width: 150, },
    {
        headerName: "操作",
        field: "action",
        width: 150,
        pinned: 'right',
        cellRenderer: {
            template: `<a-tag class="tagCss" v-if="f" @click="c">处理</a-tag>
                       <a-tag class="tagCss" v-if="!f" disabled style="color:#d1d1d1 !important">处理</a-tag>`,
            setup(props: any) {
                let val = ref(props.params.data)
                const c = () => {
                    unitHandle(props.params.data)
                }
                return {
                    c,
                    val,
                    f: props.params.data.handlerOrderCodes.indexOf(dataForm.employeeCode) > -1
                }
            },
        },
    }
]

//已判责
const gridOption2 = ref()
const colState2 = ref()
const gridReady2 = (params: any) => {
    gridOption2.value = params.api
    colState2.value = params.columnApi
}
const tableColumns2: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    {
        headerName: "来源", width: 150,
        cellRenderer: {
            template: `<span> {{ val.createUser=== 'SYN' ? '系统创建' : '手动创建' }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
    },
    { headerName: "事故单号", field: "problemCode", width: 150, },
    { headerName: "日期", field: "createTime", width: 150, },
    { headerName: "公司", field: "companyName", width: 150, },
    { headerName: "部门", field: "departmentName", width: 150, },
    { headerName: "员工工号", field: "staffCode", width: 150, },
    { headerName: "员工姓名", field: "staffName", width: 150, },
    { headerName: "机台号", field: "machineCode", width: 150, },
    { headerName: "织布单号", field: "planOrderCode", width: 150, },
    { headerName: "坯布编号", field: "greyCode", width: 150, },
    { headerName: "坯布名称", field: "greyName", width: 150, },
    {
        headerName: "数量", width: 150,
        cellRenderer: () => {
            return "<span>" + 1 + "</span>";
        },
    },
    {
        headerName: "单位", width: 150,
        cellRenderer: () => {
            return "<span>" + '匹' + "</span>";
        },
    },
    { headerName: "问题原因", field: "defectReason", width: 150, },
    { headerName: "问题补充", field: "questionSupplement", width: 150, },
    {
        headerName: "疵布重量",
        field: "lowLevelWeight",
        width: 150,
    },
    {
        headerName: "实际转数", width: 150,
        cellRenderer: (params: any) => {
            let val = params.data.convolution1 + params.data.convolution2
            return "<span>" + val + "</span>";
        },
    },
    { headerName: "责任工序", field: "handlerOrderNames", width: 150, },
    {
        headerName: "状态",
        field: "status",
        width: 150,
        pinned: 'right',
        cellRenderer: {
            template: ` <a-button v-if="val.status === 2" status="success">已处理</a-button>
                        <a-button type="primary" status="danger" v-if="val.status === 4">已驳回</a-button>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value === 2 ? '已处理' : '已驳回'
            },
        }
    },
    {
        headerName: "审核意见",
        field: "rejectReason",
        width: 150,
        pinned: 'right',
    },
    {
        headerName: "操作",
        field: "action",
        width: 160,
        pinned: 'right',
        cellRenderer: {
            template: `<a-space>
                           <el-button style="color:#165dff;" link @click="c">处理</el-button>
                       </a-space>`,
            setup(props: any) {
                const c = () => {
                    unitHandle(props.params.data)
                }
                return {
                    c,
                }
            },
        },
    },
]

const defaultColDef2: any = {
    sortable: true,
    resizable: true,
    filter: true,
    // flex: 1
}

//原因分析
const gridOptionCL = ref()
const colStateCL = ref()
const gridReadyCL = (params: any) => {
    gridOptionCL.value = params.api
    colState.value = params.columnApi
    if (pageData.sideTitle === '处理意见汇总') {
        params.columnApi.setColumnVisible('uploadImg', false)
    }
}
const tableColumnsCL: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    { headerName: "责任工序", field: "employeeName", width: 100 },
    {
        headerName: "原因分析",
        field: "problemReason",
        cellRenderer: {
            template: `<a-input :max-length="100" v-if="pageData.sideTitle === '处理意见填写'" class="bacClass" v-model="val.problemReason" allow-clear></a-input>
            <span v-else>{{ val.problemReason }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "预防措施",
        field: "preventMeasure",
        cellRenderer: {
            template: `<a-input :max-length="100" v-if="pageData.sideTitle === '处理意见填写'" class="bacClass" v-model="val.preventMeasure" allow-clear></a-input>
            <span v-else>{{ val.preventMeasure }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "处理方法",
        field: "resolution",
        cellRenderer: {
            template: `<a-input :max-length="100" v-if="pageData.sideTitle === '处理意见填写'" class="bacClass" v-model="val.resolution" allow-clear></a-input>
            <span v-else>{{ val.resolution }}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                    pageData,
                }
            },
        },
    },
    {
        headerName: "图片",
        field: "problemImg",
        cellRenderer: {
            template: ` <a-image v-if="val.problemImg" :src="val.problemImg" /> 
                        <span v-if="!val.problemImg">暂无图片</span>`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                };
            },
        },
    },
    {
        headerName: "上传图片",
        field: "uploadImg",
        cellRenderer: {
            template: `<a-upload v-if="!val.problemImg" list-type="[]" :file-list="fileInfo" :limit="1" 
                        :multipart="false" :auto-upload="false" :show-upload="false" @change="handleChange"></a-upload>
                       <icon-delete v-if="val.problemImg && pageData.sideTitle === '处理意见填写'" style="cursor: pointer;color:gray;font-size: 22px;" @click="c" />`,
            setup(props: any) {
                const val = ref(props.params.data);
                const fileInfo: any = ref([])
                //图片上传
                const handleChange = (fileInfo: any) => {
                    const file = fileInfo[0].file;
                    const fileSize = file.size / 1024 / 1024;
                    if (fileSize > 3) {
                        Message.error('上传图片不能超过3M!'); 
                        props.params.data.problemImg = null                                       
                        pageData.reasonList = [...pageData.reasonList]
                        return; 
                    }
                    const reader = new FileReader();
                    reader.readAsDataURL(fileInfo[0].file);
                    reader.onload = () => {
                        pageData.reasonList.forEach((o: any) => {
                            if (o.isTypeIds === props.params.data.isTypeIds) {
                                o.problemImg = reader.result;
                            }
                        })
                    };
                    pageData.reasonList = [...pageData.reasonList]
                };
                //删除图片
                const c = () => {
                    pageData.reasonList.forEach((o: any) => {
                        if (o.isTypeIds === props.params.data.isTypeIds) {
                            o.problemImg = null;
                        }
                    })
                    pageData.reasonList = [...pageData.reasonList]
                }
                return {
                    c,
                    fileInfo,
                    val,
                    pageData,
                    handleChange,
                };
            },
        },
    }

]

//查询
const formRef = ref<FormInstance>();
function doRefresh() {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            pageData.pageLoading = true
            post({
                url: '/qms/qualityProblem/pagedQualityProblems',
                data: {
                    current: page.value,
                    size: size.value,
                    status: tabKey.value === 1 ? 1 : null,
                    statusGroup: tabKey.value === 2 ? '2,4' : null,
                    companyId: pageData.companyId,
                    employeeCode: dataForm.employeeCode,
                    handlerDepartmentCodes: pageData.handlerDepartmentCodes === '' ? null : pageData.handlerDepartmentCodes,
                    beginTime: pageData.createTimeArr == undefined ? null : pageData.createTimeArr[0] + ' 00:00:00',
                    endTime: pageData.createTimeArr == undefined ? null : pageData.createTimeArr[1] + ' 23:59:59'
                }
            }).then((res: any) => {
                if (res.code === 200) {
                    pageData.tableList = res.data.records
                    total.value = res.data.total
                }
            }).catch(console.log).finally(() => {
                pageData.pageLoading = false
            })
        }
    })
}

const selectHandle = () => {
    page.value = 1
    doRefresh()
}

let tabKey = ref(1)
const tabChange = (e: any) => {
    tabKey.value = e
    page.value = 1
    doRefresh()
}

//处理意见 弹窗
const unitHandle = (record: any) => {
    detail(record)
    dataForm.problemId = record.id
    dataForm.handlerOrderCodes = record.handlerOrderCodes
    pageData.showAdd = true
}

//修改
const editRow = () => {
    let findCode = dataForm.handlerOrderCodes.indexOf(dataForm.employeeCode) > -1
    if (!findCode) {
        Message.warning('当前账号所属员工无权限处理！')
        return
    }
    pageData.sideTitle = '处理意见填写'
    pageData.reasonList = pageData.reasonList.filter((o: any) => o.employeeCode === dataForm.employeeCode)
    colState.value.setColumnVisible('uploadImg', true)
}

//新增行
let isTypeIds = 0
const addRow = () => {
    pageData.reasonList.push({
        'problemId': dataForm.problemId,
        'employeeCode': dataForm.employeeCode,
        'employeeName': dataForm.employeeName,
        'problemReason': '',
        'preventMeasure': '',
        'resolution': '',
        'isTypeIds': isTypeIds++
    })
    setTimeout(function () { gridOptionCL.value.setRowData(pageData.reasonList) }, 0)
}

//删除行
const delRow = () => {
    if (gridOptionCL.value.getSelectedRows().length == 0) {
        Message.warning('请选择要删除的数据！')
        return
    }
    let deleteId = pageData.reasonList.map((item: any) => item.isTypeIds);
    let deleteIds = gridOptionCL.value.getSelectedRows().map((item: any) => item.isTypeIds);
    let list = deleteId.filter((ids: any) => deleteIds.includes(ids));
    pageData.reasonList = pageData.reasonList.filter((item: any) => !list.includes(item.isTypeIds));
}

//保存
const sideOk = () => {
    if (pageData.reasonList.length === 0) {
        Message.warning('请先填写处理意见！')
        return
    }
    if (pageData.reasonList.find((o: any) => o.problemReason == '')) {
        Message.warning('原因分析必填！')
        return
    }
    pageData.reasonList.forEach((o: any) => {
        if (o.id) {
            delete o.id
        }
    })
    pageData.pageLoading = true
    post({
        url: '/qms/qualityResolution/saveOrUpdateQualityResolution',
        data: pageData.reasonList
    }).then((res: any) => {
        if (res.code === 200) {
            pageData.pageLoading = false
            pageData.showAdd = false
            selectHandle()
        }
    })
}

//处理意见
const detail = (record: any) => {
    pageData.pageLoading = true
    post({
        url: '/qms/qualityResolution/listQualityResolutions',
        data: {
            problemId: record.id
        }
    }).then((res: any) => {
        if (res.code === 200) {
            if (res.data.length === 0) {
                pageData.sideTitle = '处理意见填写'
                colState.value.setColumnVisible('uploadImg', true)
            } else {
                pageData.sideTitle = '处理意见汇总'
                colState.value.setColumnVisible('uploadImg', false)
            }
            pageData.reasonList = res.data
            pageData.reasonList.forEach((item: any) => {
                item['isTypeIds'] = isTypeIds++
            })
            pageData.pageLoading = false
        }
    })
}

//提交厂长审核
const submitAudit = () => {
    if (gridOption2.value.getSelectedRows().length === 0) {
        Message.warning('请先勾选数据!')
        return
    }
    let filterData = gridOption2.value.getSelectedRows().find((o: any) => o.status === 4);
    console.log(filterData);

    if (filterData) {
        Message.warning(`事故单号为 ${filterData.problemCode} 的状态是已驳回，请修改后再提交审核！`);
        return;
    }

    Modal.confirm({
        title: '系统提示',
        content: '是否确认提交选中的数据?',
        onOk() {
            post({
                url: '/qms/qualityProblem/commitQualityProblem',
                data: gridOption2.value.getSelectedRows(),
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: '提交成功',
                        duration: 5000,
                    })
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    })
                }
                doRefresh()
            })
        },
    })

}

//获取当前登录账号
const getUserToken = () => {
    post({
        url: 'admin/acl/user/findUserToken',
    }).then((res: any) => {
        if (res.code === 200) {
            dataForm.employeeCode = res.data.data.empMap.code
            dataForm.employeeName = res.data.data.empMap.name
            selectHandle()
        }
    })
}

const configCascader = ref<{}>({
    corporateWidth: '230px', //公司宽度
    sectorWidth: '230px', //部门宽度
    corporateRquired: false, //公司是否必填
    size: 'small',
    corporateName: '公司', //公司label
    sectorName: '责任单位', //部门label
    cascaderShow: '', //配置部门不显示

})
const changeCascader = (data: any) => {
    const { corporateId, corporateLabel, sectorId } = data
    pageData.companyId = corporateId
    pageData.companyName = corporateLabel
    pageData.handlerDepartmentCodes = sectorId
}

onMounted(() => {
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    getUserToken()
})
</script>

<style lang='less' scoped>
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag) {
    color: #4e5969 !important;
    ;
    background-color: white;
    border-color: white;
    font-size: 14px;
}

:deep(.arco-image-img) {
    height: 25px;
}
</style>